<!--
* description: 备件订单制作_总部 新增、编辑
* author: wangml
* createdDate: 2021-3-4
-->
<template>
  <section class="editStoreReturnRegistration">
    <el-dialog
      v-dialogDrag
      :visible="curPopupsVisible"
      :title="textMap[popupsState]"
      :append-to-body="true"
      width="70%"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />
      <div class="app-container app-container-table">
        <one-table-template
          ref="multipleTable"
          :key="oneTableKey"
          :refresh-table-key="tableKey"
          :dynamic-components="tableComponents"
          :dynamic-buttons="tableButtons"
          :dynamic-api-config="apiConfig"
          :dynamic-table-cols="tableCols"
          :dynamic-form-fields="formField"
          :text-messages="{
            text:'订货种类：' + totalType + '(种)  订货总金额：' + (formField.purOrderType === 'A002' ? totalPurUrgentOrderPriceAmount : totalAmount) + '(元)'
          }"
          :dynamic-is-click-show-select="true"
          :dynamic-is-show-more-btn="true"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="false"
          :is-show-pagination="false"
          :dynamic-table-defult-height="350"
          :callback-obj="callbackObj"
        >
          <template #isCanLack="scope">
            <el-checkbox
              v-model="scope.row.isCanLack"
              true-label="1"
              false-label="0"
            />
          </template>
          <template #urgentOrderPrice="scope">
            <span>{{scope.row.urgentOrderPrice == '' || null ? scope.row.purPrice : scope.row.urgentOrderPrice }}</span>
          </template>
          <template #purQty="scope">
            <el-input
              :key="scope.col.prop"
              v-model="scope.row.purQty"
              placeholder="输入数量"
              :clearable="true"
              @change="numChange($event, scope.row, scope.col, scope.$index)"
            />
          </template>
        </one-table-template>

        <part-select
          :is-view-part.sync="isViewPart"
          :row-data="rowData"
          :chosen-list.sync="chosenList"
          :cur-select-list.sync="curSelectList"
          @selectiondataPart="selectiondata2"
        />
        <!--          @close="closePart"-->
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from './api'
import partSelect from '@/views/pa/purchasingManagement/partOrderBranchMake/partSelectNew.vue'
// import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'

export default {
  components: {
    OneTableTemplate,
    dialogHeader: () => import('@/components/dialogHeader'),
    partSelect
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: { type: Object, default: function() { return {} } }
  },

  data() {
    const viewPageCode = 'storeReturnRegistration-edit'

    return {
      tableKey: 'tableKey' + this.$utils.generateId(),
      minOrderAmount: null,
      valid: false,
      chosenList: [],
      curSelectList: [],
      totalType: 0,
      totalAmount: 0.00,
      totalPurUrgentOrderPriceAmount: 0,
      totalPurUrgentOrderPriceNotTaxAmount: 0,
      totalPurAmountNotTax: 0,
      isViewPart: false,
      rowData: {},
      apiConfig: api.rtuRegistrationInfor,
      inEditPopupsKey: 'inEditPopupsKey',
      inEditPopupsState: '',
      inEditPopupsVisible: false,
      dataForForm: {},
      selectData: {},

      // 动态组件-按钮
      tableButtons: [

        {
          compKey: 'btnKey4',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => {
            this.$utils.validataMoth(this, 'validpage')
            if (!this.valid) return
            let qtyisNull = false
            this.$refs['multipleTable'].list.every((row) => {
              if (!row['purQty']) {
                qtyisNull = true
                return false
              }
              return true
            })
            if (qtyisNull) {
              return this.$message('网格中[ 订货数量+ ]为必填项!')
            }
            const { purOrderTypeCn } = this.formField
            if (purOrderTypeCn && purOrderTypeCn === '常规订单') {
              if (!this.totalAmount || Number(this.totalAmount) < Number(this.minOrderAmount)) {
                return this.$alert(`总金额不能小于起订额度 ￥${this.minOrderAmount}！`, '提示')
              }
            }
            const curFormField = this.$utils.deepCopy(this.formField)
            curFormField.billType = curFormField.billTypeS
            delete curFormField.billTypeS
            let apiUrl = api.insertPartUsingPOST.APIUrl
            const variables = {
              ...curFormField,
              orderVariety: this.totalType,
              purAmount: this.totalAmount,
              purUrgentOrderPriceAmount: this.totalPurUrgentOrderPriceAmount,
              purUrgentOrderPriceNotTaxAmount: this.totalPurUrgentOrderPriceNotTaxAmount,
              purAmountNotTax: this.totalPurAmountNotTax,
              list: this.$utils.deepCopy(this.$refs.multipleTable.list)
            }
            if (this.popupsState === 'edit') {
              apiUrl = 'mp/e3sh/spareparts/sparePartsOrderMakingService/updatePartOrder.do'
              variables['updateControlId'] = this.dynamicEditRowData.updateControlId
              variables['purchaseOrderId'] = this.dynamicEditRowData.purchaseOrderId
              variables.list.forEach(row => {
                row['purOrderCode'] = this.dynamicEditRowData.purOrderCode
              })
            }
            if (this.valid) {
              const loading = this.$loading({ text: `正在保存，请稍等...` })
              this.$requestAPI({ apiUrl, variables }).then(res => {
                if (res.result === '1') {
                  this.$message('备件订单保存成功！')
                  this.$parent.queryTable()
                  this.closeEdit()
                } else {
                  this.$message(res.msg ? res.msg : '')
                }
              }).catch(err => {
                if (err.response.data.msg) {
                  this.$message(err.response.data.msg)
                } else {
                  this.$message(err.message)
                }
              }).finally(() => {
                loading.close()
              })
            }
          },
          text: '保存',
          position: 'right'
        },
        {
          compKey: 'btnKey4',
          type: 'primary',
          name: 'selecjinpingbeijian',
          size: 'small',
          clickEvent: () => {
            // if (!this.formField.supplierId) return this.$message('请先选择供应商!')
            this.rowData = {
              isHq: true,
              supplierId: this.formField.supplierId,
              supplierCode: this.formField.supplierCode
            }
            this.chosenList = this.$refs['multipleTable'].list.map(row => row['partId'])
            const lis = this.$utils.deepCopy(this.$refs['multipleTable'].list)
            lis.forEach(o => o['cur'] = true)
            this.curSelectList = lis
            this.isViewPart = true
          },
          text: '备件选择',
          position: 'left'
        },
        {
          compKey: 'btnKey5',
          type: '',
          name: 'quanbushanchu',
          size: 'small',
          clickEvent: () => {
            // 需要删除数据的 index 列表
            this.$refs['multipleTable'].list = this.$refs['multipleTable'].list.reduce((newList, row, idx) => {
              if (!this.selectData.map(o => o['partId']).includes(row['partId'])) {
                newList.push(row)
              }
              return newList
            }, [])
            // 重新计算 总价格
            this.totalType = this.$refs['multipleTable'].list.length
            this.caclTotal()
          },
          text: '备件删除',
          position: 'left'
        },
        {
          compKey: 'btnKey6',
          type: '',
          size: 'small',
          name: 'importTemplate',
          text: '导入',
          position: 'upload'
        },
        {
          compKey: 'button33',
          type: 'text',
          size: 'small',
          name: '',
          position: 'upload',
          text: '模板下载',
          click: event => this.templateDownload()
        },
        {
          compKey: 'btnKey7',
          type: '',
          size: 'small',
          name: 'reset',
          clickEvent: () => {
            for (const attr in this.formField) {
              if (attr !== 'purOrderCode') {
                this.formField[attr] = ''
              }
            }
          },
          text: '重置',
          position: 'right'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
            {
              compKey: 'compKey6',
              labelName: '订单号：',
              codeField: 'purOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              disabled: true,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey1',
              labelName: '网点：',
              codeField: 'dlrId',
              textField: 'dlrShortName',
              component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
              isMust: true,
              isRequire: true,
              customObj: { showType: 'text' },
              dataToObject: {
                tableComponents: [
                  {
                    compKey: 'compKey1',
                    labelName: '网点编码：',
                    codeField: 'dlrCode',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  },
                  {
                    compKey: 'compKey2',
                    labelName: '网点名称：',
                    codeField: 'dlrShortName',
                    component: () => import('@/components/org/commonInput'),
                    type: 'inputText',
                    isMust: true,
                    span: 8
                  }
                ],
                tableCols: [
                  {
                    prop: 'dlrCode',
                    label: '网点编码'
                  },
                  {
                    prop: 'dlrShortName',
                    label: '网点名称'
                  }
                ],
                formField: {
                  dlrShortName: '',
                  dlrCode: ''
                },
                oFields: 'dlrId,dlrShortName',
                returnField: {
                  prop: 'dlrShortName',
                  label: '网点名称'
                },
                api: { APIUrl: 'mp/e3sh/spareparts/finance/bonusOrderMakeService/queryOrgDlrCodes.do', ServiceCode: 'queryOrgDlrCodes' }
              },
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '订货日期：',
              codeField: 'purDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              // dateType: 'daterange',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '订单类型：',
              codeField: 'purOrderType',
              textField: 'purOrderTypeCn',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: api.findOrderTypeListUsingPOST,
                selectType: '1'
              },
              oFields: 'orderTypeCode,orderTypeName',
              type: 'dropdownList',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            // {
            //   compKey: 'compKey4',
            //   labelName: '运输方式：',
            //   codeField: 'transportModeId',
            //   textField: 'transportModeName',
            //   component: () => import('@/components/org/commonSelect'),
            //   parentFileds: 'disabled:purOrderType-transportModeId--false',
            //   options: [1],
            //   disabled: true,
            //   oFields: 'transportModeId,transportModeName',
            //   type: 'dropdownList',
            //   isMul: false,
            //   isMust: true,
            //   isRequire: true,
            //   span: 8
            // },
            // {
            //   compKey: 'compKey5',
            //   labelName: '供应商：',
            //   codeField: 'supplierId',
            //   textField: 'supplierShortName',
            //   otherField: 'supplierCode',
            //   component: () => import('@/views/ve/planReport/components/multipleSearchInput'),
            //   type: 'inputText',
            //   isMul: false,
            //   isMust: true,
            //   isRequire: true,
            //   customObj: {
            //     showType: 'text'
            //   },
            //   dataToObject: {
            //     // 控制弹窗页面 搜索 网格 元素
            //     oFields: 'supplierId,supplierShortName',
            //     tableComponents: [
            //       {
            //         compKey: 'compKey1',
            //         labelName: '供应商编码：',
            //         codeField: 'supplierCode',
            //         component: () => import('@/components/org/commonInput'),
            //         type: 'inputText',
            //         isMust: true,
            //         span: 8
            //       },
            //       {
            //         compKey: 'compKey2',
            //         labelName: '供应商名称：',
            //         codeField: 'supplierShortName',
            //         component: () => import('@/components/org/commonInput'),
            //         type: 'inputText',
            //         isMust: true,
            //         span: 8
            //       }
            //     ],
            //     tableCols: [
            //       {
            //         prop: 'supplierCode',
            //         label: '供应商编码'
            //       },
            //       {
            //         prop: 'supplierShortName',
            //         label: '供应商名称'
            //       }
            //     ],
            //     formField: {
            //       supplierCode: '',
            //       supplierShortName: ''
            //     },
            //     returnField: {
            //       prop: 'supplierCode',
            //       label: '供应商编码'
            //     },
            //     api: { ServiceCode: 'queryPartSources', APIUrl: '/mp/e3sh/spareparts/sparePartsOrderMakingService/querySupplierCode.do' }
            //   },
            //   span: 8
            // },

            {
              compKey: 'compKey7711',
              labelName: '结算方式：',
              codeField: 'billType',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'isBillType,isBillTypeCn',
              isRequire: true,
              options: [1],
              isMust: true,
              span: 8
            },
          ],
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'isCanLack',
              label: '可欠拨',
              width: 50,
              align: 'center',
              isSlot: true
            },
            {
              prop: 'purPriceNotTax',
              label: '隐藏字段',
              width: 50,
              align: 'center',
              hidden: true
            },
            {
              prop: 'partNo',
              label: '备件号',
              align: 'center'
            },
            {
              prop: 'partName',
              label: '备件名称',
              align: 'center'
            },
            {
              prop: 'unit',
              label: '计量单位',
              align: 'center'
            },
            {
              prop: 'snp',
              label: 'SNP',
              align: 'center'
            },
            {
              prop: 'minPurchasePage',
              label: '最小订货数',
              align: 'center'
            },
            {
              prop: 'purPrice',
              label: '单价',
              align: 'center',
              hidden: false
            },
            {
              prop: 'urgentOrderPrice',
              label: '单价',
              align: 'center',
              hidden: true,
              isSlot:true
            },
            {
              prop: 'purQty',
              label: '订货数量+',
              align: 'center',
              isSlot: true
            },
            {
              prop: 'purAmount',
              label: '订货金额',
              align: 'center',
              hidden: false
            },
            {
              prop: 'purUrgentOrderPriceAmount',
              label: '订货金额',
              align: 'center',
              hidden: true
            },
            {
              // prop: 'kyqty',
              prop: 'accountQty',
              label: '库存数量',
              align: 'center'
            },
            {
              // prop: 'sjqty',
              prop: 'usableQty',
              label: '可用库存',
              align: 'center'
            },
            {
              prop: 'underdialQty',
              label: '有效欠拨数量',
              align: 'center'
            },

            // {
            //   prop: 'assignWorkCode',
            //   label: '派工单号',
            //   align: 'center'
            // }
            // {
            //   prop: 'vin',
            //   label: 'VIN码+',
            //   align: 'center'
            // },
            // {
            //   prop: 'carLicense',
            //   label: '车牌号+',
            //   align: 'center'
            // },
            // {
            //   prop: 'custName',
            //   label: '客户名称+',
            //   align: 'center'
            // },
            // {
            //   prop: 'custTel',
            //   label: '客户电话+',
            //   align: 'center'
            // }
          ],
      // 标题
      textMap: {
        edit: '总部备件订单编辑',
        add: '总部备件订单新增'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(this, {
        dlrId: '',
        dlrShortName: '',
        purDate: '',
        purOrderType: '',
        purOrderTypeCn: '',
        transportModeId: '',
        transportModeName: '',
        supplierId: '',
        supplierShortName: '',
        supplierCode: '',
        purOrderCode: '',
        billType: '',
        billTypeS: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          // this.handleSelectionChange(selection)
        }
      }
    }
  },

  watch: {
    'formField.purOrderType': {
      handler(type) {
        this.showPriceByOrderType(type)
        
        // 订单类型改变，将purOrderTypeCn的后两位添插入订单号中
        let orderType=type.slice(-2)
        let oldCode=this.formField.purOrderCode.split("")
        oldCode.splice(2,2,orderType)
        this.formField.purOrderCode = oldCode.join("")
      },
      immediate: true
    },
    'formField.supplierId': {
      handler: function(val) {
        this.$nextTick(() => {
          if (this.$refs['multipleTable']) {
            this.$refs['multipleTable'].list = []
          }
        })
        this.totalType = 0
        this.totalAmount = 0
      },
      immediate: true
    },
    'formField.billType': {
      handler(val) {
        if (val) {
          if (val === '0') {
            this.formField.billTypeS = '1'
          } else {
            this.formField.billTypeS = '2'
          }
        } else {
          this.formField.billTypeS = ''
        }
      }
    },
    'formField.dlrId': {
      handler(val) {
        const comp = this.tableComponents.find(comp => comp.codeField === 'billType')
        comp.disabled = !val
        comp.compKey = 'billType' + this.$utils.generateId()
        this.formField.billType = ''
        if (val) {
          this.loadBillType(val)
        }
      },
      immediate: true
    },
  },
  mounted() {
    // 加载起订金额
    this.getMinOrderAmount()
    // 加载默认信息
    this.loadDefaultInfo()
    // 赋值 订单种类 和 订单总金额
    if (this.popupsState === 'edit') {
      this.$nextTick(() => {
        this.totalType = this.dynamicEditRowData.orderVariety
        this.totalAmount = this.dynamicEditRowData.purAmount
      })
    } else {
      this.addDate()
    }
  },

  methods: {
    // 获取当前年月日
    addDate() {
      const nowDate = new Date()
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      }
      const newmonth = date.month > 10 ? date.month : '0' + date.month
      const day = date.date > 10 ? date.date : '0' + date.date
      this.formField.purDate = date.year + '-' + newmonth + '-' + day
    },
    showPriceByOrderType(type) {
      if (type === 'A002') {
        // 选择了紧急订单
        this.tableCols.find(col => col.prop === 'purPrice').hidden = true
        this.tableCols.find(col => col.prop === 'urgentOrderPrice').hidden = false
        this.tableCols.find(col => col.prop === 'purAmount').hidden = true
        this.tableCols.find(col => col.prop === 'purUrgentOrderPriceAmount').hidden = false
      } else {
        this.tableCols.find(col => col.prop === 'purPrice').hidden = false
        this.tableCols.find(col => col.prop === 'urgentOrderPrice').hidden = true
        this.tableCols.find(col => col.prop === 'purAmount').hidden = false
        this.tableCols.find(col => col.prop === 'purUrgentOrderPriceAmount').hidden = true
      }
      this.tableKey = 'tableKey' + this.$utils.generateId()
    },
    //   /mp/e3sh/spareparts/TariffAdjustService/getMinOrderAmount.do
    async getMinOrderAmount() {
      let response
      const apiUrl = '/mp/e3sh/spareparts/TariffAdjustService/getMinOrderAmount.do'
      try { response = await this.$requestAPI({ apiUrl, method: 'GET' }) } catch (e) { return false }
      if (response.result !== '1') { return this.$message(response.msg || '起订金额获取失败!') }
      this.minOrderAmount = response.rows[0].ATTRIBUTE1
    },
    async loadTransport(orderTypeId) {
      let response
      const apiUrl = '/mp/e3sh/spareparts/OrderTypeAndTransportService/queryTransport.do'
      const variables = { orderTypeId }
      try { response = await this.$requestAPI({ apiUrl, variables }) } catch (e) { return false }
      if (response.result !== '1') { return this.$message(response.msg || '运输方式加载失败!') }
      this.tableComponents.find(comp => comp.codeField === 'transportModeId').options = response.rows
    },
    async loadBillType(dlrId) {
      let response
      const apiUrl = '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/findDlrBillType.do'
      const variables = { dlrId }
      try { response = await this.$requestAPI({ apiUrl, variables }) } catch (e) { return false }
      if (response.result !== '1') {
        this.tableComponents.find(comp => comp.codeField === 'billType').options = []
        return this.$message(response.msg || '结算方式加载失败!')
      }
      this.$nextTick(() => {
        this.tableComponents.find(comp => comp.codeField === 'billType').options = response.rows
      })
      if (!response.rows.map(opt => opt['disabled']).includes(false)) {
        await this.$alert('该网点账户未开启结算方式!', '提示')
      }
    },
    addIndex(rows) {
      rows.forEach((row, index) => {
        row['index'] = index
      })
      return rows
    },
    loadSubData() {
      this.$requestAPI({
        apiUrl: 'mp/e3sh/spareparts/sparePartsOrderMakingService/queryOrderDetails.do',
        variables: { purchaseOrderId: this.dynamicEditRowData.purchaseOrderId }
      }).then(res => {
        if (res.result === '1') {
          this.$refs['multipleTable'].list = this.addIndex(res.rows)
          this.calcTotals()
        } else {
          this.$message(res.msg ? res.msg : '')
        }
      }).catch(err => {
        if (err.response.data.msg) {
          this.$message(err.response.data.msg)
        } else {
          this.$message(err.message)
        }
      })
    },

    loadDefaultInfo() {
      if (this.popupsState === 'edit') {
        // 赋值 formField
        for (const attr in this.formField) {
          if (this.dynamicEditRowData.hasOwnProperty(attr)) {
            if (attr === 'billType') {
              this.$nextTick(() => {
                this.formField.billType = (Number(this.dynamicEditRowData[attr]) - 1).toString()
              })
            } else {
              this.formField[attr] = this.dynamicEditRowData[attr]
            }
          }
        }
        // 加载 子表数据
        this.loadSubData()
      } else {
        // 从vuex 获取网点数据
        // const {DLR_ID, DLR_NAME, DLR_CODE} = this.$store.state.user.orgInfo
        // this.formField.dlrId = DLR_ID
        // this.formField.dlrShortName = DLR_NAME

        const queryObj1 = {
          apiConfig: {
            ServiceCode: 'queryPartOrderCode',
            APIUrl: 'mp/e3sh/spareparts/sparePartsOrderMakingService/queryOrderCode.do'
          },
          variables: {}
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj1)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then(response => {
          const { purOrderCode, supplierCode, supplierId, supplierShortName } = response.rows[0]
          this.formField.purOrderCode = purOrderCode
          this.formField.supplierCode = supplierCode
          this.formField.supplierId = supplierId
          this.formField.supplierShortName = supplierShortName
        })
      }
    },
    numChange(val, row, col, index) {
      const errorReset = msg => {
        row[col['prop']] = ''
        row['purAmount'] = '0.00'
        val ? this.$alert(msg, '提示') : ''
      }
      const panter = /c|(^[1-9][0-9]*$)/
      if (!panter.test(val)) {
        errorReset('请输入正确的订货数量!')
      } else if (Number(val) < Number(row['minPurchasePage'])) {
        errorReset('[ 订货数量 ] 不能小于 [ 最小订货量 ]！')
      } else if (Number(val) % Number(row['snp'])) {
        errorReset('[ 订货数量 ] 只能为 [ SNP ]的倍数!')
      } else {
        this.$set(row, 'purAmount', (Number(val) * Number(row['purPrice'])).toFixed(2))
        this.calcOtherPrice(row)
      }
      // 计算 总计
      // this.caclTotal()
      this.totalType = this.$refs['multipleTable'].list.length
      this.calcTotals()
    },
    caclTotal() {
      // purAmount = purQty * purPrice
      this.totalType = this.$refs['multipleTable'].list.length
      this.totalAmount = this.$refs['multipleTable'].list.reduce((amount, row) => {
        return amount + Number(row['purAmount'])
      }, 0)
    },
    closePart() {
      this.isViewPart = false
    },
    calcOtherPrice(row) {
      // 数量
      const purQty = Number(row['purQty'])
      //单价
      const purPrice = Number(row['purPrice'])
      // 浮动价（含税）
      const urgentOrderPrice = Number(row['urgentOrderPrice'])
      // 浮动价 （不含税）
      const urgentOrderPriceNotTax = Number(row['urgentOrderPriceNotTax'])
      // 正常订单价不含税
      let purPriceNotTax = Number(row['purPriceNotTax'])
      // 计算 总浮动价 （含税） urgentOrderPrice * purQty
      let purUrgentOrderPriceAmount = urgentOrderPrice ==  0 ? (purPrice * purQty).toFixed(2) : (urgentOrderPrice * purQty).toFixed(2)
      // const purUrgentOrderPriceAmount = urgentOrderPrice * purQty
      // 计算 总浮动价 （不含税）urgentOrderPriceNotTax * purQty
      let purUrgentOrderPriceNotTaxAmount = urgentOrderPriceNotTax * purQty
      // 计算 总正常订单价 （不含税） purPriceNotTax * purQty
      let purAmountNotTax = purPriceNotTax * purQty
      // 赋值
      row['purUrgentOrderPriceAmount'] = purUrgentOrderPriceAmount
      row['purUrgentOrderPriceNotTaxAmount'] = purUrgentOrderPriceNotTaxAmount
      row['purAmountNotTax'] = purAmountNotTax
    },
    calcTotals() {
      const {
        totalAmount,
        totalPurUrgentOrderPriceAmount,
        totalPurUrgentOrderPriceNotTaxAmount,
        totalPurAmountNotTax
      } = this.$refs['multipleTable'].list.reduce((amount, row) => {
        const totalAmount = amount['totalAmount']
        const totalPurUrgentOrderPriceAmount = amount['totalPurUrgentOrderPriceAmount']
        const totalPurUrgentOrderPriceNotTaxAmount = amount['totalPurUrgentOrderPriceNotTaxAmount']
        const totalPurAmountNotTax = amount['totalPurAmountNotTax']
        amount['totalAmount'] = totalAmount + (Number(row['purAmount']) || 0)
        amount['totalPurUrgentOrderPriceAmount'] = totalPurUrgentOrderPriceAmount + (Number(row['purUrgentOrderPriceAmount']) || 0)
        amount['totalPurUrgentOrderPriceNotTaxAmount'] = totalPurUrgentOrderPriceNotTaxAmount + (Number(row['purUrgentOrderPriceNotTaxAmount']) || 0)
        amount['totalPurAmountNotTax'] = totalPurAmountNotTax + (Number(row['purAmountNotTax']) || 0)
        return amount
      }, {
        totalAmount: 0,
        totalPurUrgentOrderPriceAmount: 0,
        totalPurUrgentOrderPriceNotTaxAmount: 0,
        totalPurAmountNotTax: 0
      })
      this.totalAmount = totalAmount.toFixed(2)
      this.totalPurUrgentOrderPriceAmount = totalPurUrgentOrderPriceAmount.toFixed(2)
      this.totalPurUrgentOrderPriceNotTaxAmount = totalPurUrgentOrderPriceNotTaxAmount.toFixed(2)
      this.totalPurAmountNotTax = totalPurAmountNotTax.toFixed(2)
    },
    // 备件选择
    selectiondata2(selectiondata) {
      selectiondata.forEach(row => {
        // 设置默认可欠拨
        if (!('isCanLack' in row)) { this.$set(row, 'isCanLack', '1') }
        // 设置默认订货数量
        if (!row['cur']) { row['purQty'] = row['minPurchasePage'] }
        this.calcOtherPrice(row)
      })
      this.$refs['multipleTable'].list = selectiondata
      this.$nextTick(() => {
        this.totalType = this.$refs['multipleTable'].list.length
        this.$refs['multipleTable'].list.forEach(row => {
          this.$set(row, 'purAmount', (Number(row['purQty']) * Number(row['purPrice'])).toFixed(2))
        })
        this.calcTotals()
      })
    },
    inEdit() {
      this.inEditPopupsVisible = true
      this.dataForForm = this.formField
    },
    // 批量导入模板下载
    templateDownload() {
      const fileName = this.$utils.fileNameWithTime('备件订单制作_总部模板.xlsx')
      this.$requestAPI({
        apiUrl:
          '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/getPartOrderExcelTemplate.do',
        variables: { dataType: 'excel' }
      })
        .then(res => {
          this.$utils.downloadFile(res, fileName)
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpage')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.rtuRegistrationUpd,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.$emit('update:popupsVisible', false)
          this.$parent.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.rtuRegistrationAdd,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.$emit('update:popupsVisible', false)
          this.$parent.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    deleteDatas() {
      const that = this
      const queryObj = {
        type: 'mutation',
        apiConfig: api.coreInfoDel,
        variables: {
          list: that.selectData.reduce((pre, cur, idx) => {
            const { partId } = cur
            console.log({ partId })
            pre.push({ partId })
            return pre
          }, [])
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    closeEdit() {
      this.$emit('update:popups-visible', false)
    },

    // 关闭保存弹窗
    closeInEdit() {
      this.inEditPopupsVisible = false
      this.inEditPopupsKey = this.$utils.generateId()
    },

    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType != 'xls' && fileType != 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const that = this
      const url =
        '/mp/e3sh/spareparts/mallorder/partOrderMakeDlrService/importPartOrderExcel.do'
      that
        .$requestUpload(url, param, {
          code: this.formField.supplierCode
        })
        .then(response => {
          if (response.result === '1') {
            if(!this.$refs.multipleTable.list.length){
              this.$refs.multipleTable.list = response.rows
            } else {
              const partIds = this.$refs.multipleTable.list.map(row => row['partId'])
              response.rows.forEach((element, index) => {
                if (!partIds.includes(element['partId'])) {
                  // 若数据不存在 则加入网格
                  this.$refs.multipleTable.list.push(element)
                } else {
                  // 数据存在,替换
                  this.$refs['multipleTable'].list[
                    this.$refs['multipleTable'].list.findIndex(o => o['partId'] === element['partId'])
                  ] = element
                }
              })
            }            
            // 加索引
            this.$refs['multipleTable'].list.forEach((row, index) => {
              row['index'] = index
              let sum = Number((Number(row.purPrice) * Number(row.purQty)).toFixed(2))
              that.$set(row,'purAmount',sum)
              that.totalAmount +=  sum
            })
            let queryLength = this.$refs['multipleTable'].list.length
            that.totalType = queryLength == undefined || null ? 0 : queryLength
            this.$message({
              message: '导入成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: response.msg,
              type: 'warning'
            })
          }
        })
        .catch(err => {})
        .finally(() => {
          loading.close()
        })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>

